package org.snail.other.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.dingtalk.open.client.api.model.corp.*;
import com.dingtalk.open.client.common.SdkInitException;
import com.dingtalk.open.client.common.ServiceException;
import com.dingtalk.open.client.common.ServiceNotExistException;
import lombok.extern.log4j.Log4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.snail.common.dingding.utils.JedisUtils;
import org.snail.message.service.impl.GroupMessagePushService;
import org.snail.attendence.bean.AbnormalAttendanceDTO;
import org.snail.attendence.bean.AttendenceMessage;
import org.snail.common.FileUtils;
import org.snail.constant.*;
import org.snail.common.dingding.auth.AuthHelper;
import org.snail.common.dingding.chat.ChatHelper;
import org.snail.common.dingding.exception.OApiException;
import org.snail.common.dingding.media.MediaHelper;
import org.snail.employee.mapper.EmployeesMapper;
import org.snail.exception.BaseException;
import org.snail.exception.CommonException;
import org.snail.exception.EmpException;
import org.snail.exception.GroupException;
import org.snail.other.bean.GroupDO;
import org.snail.other.bean.GroupNotificationDTO;
import org.snail.attendence.mapper.AttendenceMongoMapper;
import org.snail.other.bean.GroupNotificationSendDTO;
import org.snail.other.mapper.GroupMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.*;


//获取需要补卡人员的信息,发送补卡提示
@Service
@Log4j
public class SendMessageServiceImpl {

    @Autowired
    private AttendenceMongoMapper attendenceMongoMapper;

    @Autowired
    private GroupMapper groupMapper;

    @Autowired
    private JedisUtils jedisUtils;

    @Autowired
    private GroupMessagePushService groupMessagePushService;

    @Autowired
    private EmployeesMapper employeesMapper;
    @Value("${server.online.flag}")
    private int normalFlag;

    //群消息发送的文件下载路径
    private String groupMessageFilePath;
    private String mediaId;

    private String messageFilePath = "";

    private static Map<Integer, String> messageMap = new HashMap<>();
    String onePhone = "";
    Map<Integer, String> seandMessageMap = new LinkedHashMap();//消息
    String WEBHOOK_TOKEN = "";


    public String fillCard(List<AbnormalAttendanceDTO> sendMessageDTOS) throws CommonException {
        String finalMsg = null;
        List<AttendenceMessage> attendenceMessageList = null;
        seandMessageMap = new HashMap();
        attendenceMessageList = attendenceMongoMapper.findAttendaceMessage();
        Map<Integer, List<AbnormalAttendanceDTO>> empId_ListMap = new LinkedHashMap<>();

        for (AbnormalAttendanceDTO abnormalAttendanceDTO : sendMessageDTOS) {
            //1.判断是否是同一个人
            Integer empId = abnormalAttendanceDTO.getEmpId();
            if (null == empId || empId < 1) {
                log.error("==============从异常考勤数据库中取出的员工主键为空！考勤明细：" + abnormalAttendanceDTO);
                continue;
            }
            if (!empId_ListMap.containsKey(empId)) {
                empId_ListMap.put(empId, new ArrayList<>());       //创建一个list
            }
            List<AbnormalAttendanceDTO> abnormalAttendanceDTOS = empId_ListMap.get(empId);
            abnormalAttendanceDTOS.add(abnormalAttendanceDTO);
        }
        //遍历map
        for (Map.Entry<Integer, List<AbnormalAttendanceDTO>> oneAbAttList : empId_ListMap.entrySet()) {
            if (null == oneAbAttList || null == oneAbAttList.getValue() || oneAbAttList.getValue().isEmpty()) {
                log.error("发送钉钉时，传入的异常考勤List没有数据! 员工id:" + oneAbAttList.getKey() + "异常考勤列表：" + oneAbAttList.getValue());
                continue;
            }
            Map<Integer, String> empId_notifyMap = editMessage(oneAbAttList.getValue());
            String messageContent = empId_notifyMap.get(oneAbAttList.getKey());
            String textMsg = "{ 'msgtype': 'text', 'text': { 'content': '" + messageContent + "' }, 'at': { 'atMobiles': [ '" + onePhone + "',], 'isAtAll': false } }";
            finalMsg = sendMessage(textMsg, WEBHOOK_TOKEN);
        }
        return finalMsg;
    }


    /**
     * @param sendMessageDTOS
     * @return seandMessageMap
     * @function 编辑员工消息
     */
    private Map<Integer, String> editMessage(List<AbnormalAttendanceDTO> sendMessageDTOS) {
        seandMessageMap = new HashMap<>();
        List<AbnormalAttendanceDTO> cardMissDayList = new ArrayList<AbnormalAttendanceDTO>();      //忘記打卡
        List<AbnormalAttendanceDTO> workUnder9List = new ArrayList<AbnormalAttendanceDTO>();     //工作小于九小时
        List<AbnormalAttendanceDTO> lateList = new ArrayList<AbnormalAttendanceDTO>();          //迟到
        List<AbnormalAttendanceDTO> forgetLeaveList = new ArrayList<AbnormalAttendanceDTO>();  //忘记在微信上请假的列表
        for (AbnormalAttendanceDTO sendMessageDTO : sendMessageDTOS) {
            onePhone = sendMessageDTO.getPhone();
            WEBHOOK_TOKEN = sendMessageDTO.getHookurl();
            if (StringUtils.isEmpty(onePhone) || StringUtils.isEmpty(WEBHOOK_TOKEN)) {
                log.error("mongoDB异常考勤中缺失重要参数！异常考勤：" + sendMessageDTO);
                continue;
            }
            if (WorkSheetConstant.ABNORMAL_RESULT_MISS_DAY.equals(sendMessageDTO.getAbnormalityOfAttendance())
                    || WorkSheetConstant.ABNORMAL_RESULT_MISS_NIGHT.equals(sendMessageDTO.getAbnormalityOfAttendance())
                    || WorkSheetConstant.ABNORMAL_RESULT_MISS_BOTH.equals(sendMessageDTO.getAbnormalityOfAttendance())) {
                cardMissDayList.add(sendMessageDTO);
            }
            if (WorkSheetConstant.ABNORMAL_RESULT_UNDER9.equals(sendMessageDTO.getAbnormalityOfAttendance()) || WorkSheetConstant.ABNORMAL_RESULT_SPECIAL_UNDER9.equals(sendMessageDTO.getAbnormalityOfAttendance())) {
                workUnder9List.add(sendMessageDTO);
            }
            if (WorkSheetConstant.ABNORMAL_RESULT_SERIOUS_LATE.equals(sendMessageDTO.getAbnormalityOfAttendance())) {
                lateList.add(sendMessageDTO);
            }
            if (WorkSheetConstant.ABNORMAL_FORGET_LEAVE.equals(sendMessageDTO.getAbnormalityOfAttendance())) {
                forgetLeaveList.add(sendMessageDTO);
            }
        }
        if (null != cardMissDayList && cardMissDayList.size() > 0) {    //忘記打卡
            for (AbnormalAttendanceDTO sendMessageDTO : cardMissDayList) {
                String message = messageMap.get(2);
                Integer empId = sendMessageDTO.getEmpId();
                String name = sendMessageDTO.getEmployeeName();
                String date = getMessageDate(sendMessageDTO, cardMissDayList);
                if (seandMessageMap.containsKey(empId)) {
                    seandMessageMap.put(empId, seandMessageMap.get(empId) + date);
                } else {
                    seandMessageMap.put(empId, name + "\t缺卡【" + message + "】：" + date);//待优化
                }
            }
        }
        if (null != workUnder9List && workUnder9List.size() > 0) {   //<9小時
            Set<Integer> set = new LinkedHashSet<Integer>();
            for (AbnormalAttendanceDTO sendMessageDTO : workUnder9List) {
                String message9 = messageMap.get(1);
                Integer empId = sendMessageDTO.getEmpId();
                String name = sendMessageDTO.getEmployeeName();
                String date = getMessageDate(sendMessageDTO, workUnder9List);
                if (seandMessageMap.containsKey(empId)) {
                    if (set.contains(empId)) {
                        seandMessageMap.put(empId, seandMessageMap.get(empId) + date);//待优化
                    } else {
                        seandMessageMap.put(empId, seandMessageMap.get(empId) + "\n工作时长小于9小时【" + message9 + "】：" + date);
                        set.add(empId);
                    }
                } else {
                    seandMessageMap.put(empId, name + "\t工作时长小于9小时【" + message9 + "】：" + date);
                    set.add(empId);
                }
            }
        }
        if (null != lateList && lateList.size() > 0) {
            Set<Integer> set = new LinkedHashSet<Integer>();
            for (AbnormalAttendanceDTO sendMessageDTO : lateList) {
                Integer empId = sendMessageDTO.getEmpId();
                String name = sendMessageDTO.getEmployeeName();
                String date = sendMessageDTO.getDateStr() + ",\t";
                if (seandMessageMap.containsKey(empId)) {
                    if (set.contains(empId)) {
                        seandMessageMap.put(empId, seandMessageMap.get(empId) + date);
                    } else {
                        seandMessageMap.put(empId, seandMessageMap.get(empId) + "\n严重迟到:" + date);
                        set.add(empId);
                    }
                } else {
                    seandMessageMap.put(empId, name + "\t严重迟到:" + date);
                    set.add(empId);
                }
            }
        }
        //加入微信事假提醒的list send的类型为3
        if (!forgetLeaveList.isEmpty()) {
            Set<Integer> set = new LinkedHashSet<Integer>();
            for (AbnormalAttendanceDTO sendMessageDTO : forgetLeaveList) {
                String forgetMessage = messageMap.get(3);
                Integer empId = sendMessageDTO.getEmpId();
                String date = sendMessageDTO.getDateStr() + ",\t";
                if (seandMessageMap.containsKey(empId)) {
                    if (set.contains(empId)) {
                        seandMessageMap.put(empId, seandMessageMap.get(empId) + date);
                    } else {
                        seandMessageMap.put(empId, seandMessageMap.get(empId) + "\n微信事假未申请【】:" + date);
                        set.add(empId);
                    }
                } else {
                    seandMessageMap.put(empId, "微信事假未申请【" + forgetMessage + "】:" + date);
                    set.add(empId);
                }
            }

        }
        return seandMessageMap;
    }

    /**
     * 美化钉钉异常消息显示
     *
     * @param sendMessageDTO
     * @param list
     * @return 换行时使用;   不换行时使用,
     */
    private static String getMessageDate(AbnormalAttendanceDTO sendMessageDTO, List<AbnormalAttendanceDTO> list) {
        String date = null;
        String outNum = sendMessageDTO.getAliNumber();
        if (outNum != "" && outNum != null) {
            date = sendMessageDTO.getDateStr() + ",\t";
        }
        return date;
    }

    /**
     * @param textMsgs
     * @param WEBHOOK_TOKEN
     * @return
     * @function 向群推送消息
     */
    private String sendMessage(String textMsgs, String WEBHOOK_TOKEN) {
        //String WEBHOOK_TOKEN = "https://oapi.dingtalk.com/robot/send?access_token=f052c29c76da817538b5b44ad43d16ff6112610273bf46681f8249a84d7dbf24";
        try {
            HttpClient httpclient = HttpClients.createDefault();

            HttpPost httppost = new HttpPost(WEBHOOK_TOKEN);
            httppost.addHeader("Content-Type", "application/json; charset=utf-8");

            String textMsg = textMsgs;
            StringEntity se = new StringEntity(textMsg, "utf-8");
            httppost.setEntity(se);

            HttpResponse response = httpclient.execute(httppost);
            if (200 == response.getStatusLine().getStatusCode()) {
                String result = EntityUtils.toString(response.getEntity(), "utf-8");
            }
            return "向群推送消息成功";
        } catch (Exception e) {
            log.info("向群推送消息失败", e);
        }
        return "向群推送消息失败";
    }

    public String groupNotification(GroupNotificationDTO groupNotificationDTO) throws EmpException {
//        String WEBHOOK_TOKEN = "https://oapi.dingtalk.com/robot/send?access_token=f052c29c76da817538b5b44ad43d16ff6112610273bf46681f8249a84d7dbf24";
        String WEBHOOK_TOKEN = null;
        String pictureURL = "![图片](" + groupNotificationDTO.getPictureURL() + ")\n";//图片URL
        String text = groupNotificationDTO.getText();
        Integer sendType = groupNotificationDTO.getSendType();
        String finalMsg = null;
        String textMsg = null;
        if (StringUtils.isEmpty(groupNotificationDTO.getPictureURL())) {
            pictureURL = "";
        }
        //设置发送的类型
        if (groupNotificationDTO == null) {
            throw new EmpException(ErrCodeConstant.ILLEGAL_PARAM, "群发消息参数不能为空");
        }
        if (GroupMsgConstant.CONTEXT_MSG == groupNotificationDTO.getSendType()) {
            textMsg = "{ \"msgtype\": \"text\", " +
                    "         \"text\": {\"" +
                    "content\": \"" + text + "\"}}";
        } else if (GroupMsgConstant.PIC_MSG == groupNotificationDTO.getSendType()) {
//            textMsg = "{\n" +
//                    "    \"actionCard\": {\n" +
//                    "        \"title\":\" " + title + "\", \n" +
//                    "        \"text\": \"" + pictureURL +
//                    " ### " + title + " \n" +
//                    text + "\",\n" +
//                    "        \"hideAvatar\": \"0\", \n" +
//                    "        \"btnOrientation\": \"0\", \n" +
//                    "        \"singleTitle\" : \"阅读全文\",\n" +
//                    "        \"singleURL\" : \"" + linkPath + "\"\n" +
//                    "    }, \n" +
//                    "    \"msgtype\": \"actionCard\"\n" +
//                    "}";
//            textMsg = "{\n" +
//                    "     \"msgtype\": \"markdown\",\n" +
//                    "     \"markdown\": {\n" +
//                    "         \"title\":\"" + title + "\",\n" +
//                    "         \"text\": \"" + pictureURL + "\n### " + title + "\n" + " " + "\n" +
//                    ">###### " + text +
//                    "    \" },\n" +
//                    "    \"at\": {\n" +
//                    "        \"atMobiles\": [ ],\n" +
//                    "        \"isAtAll\": true\n" +
//                    "    }\n" +
//                    " }";
        } else if (GroupMsgConstant.LINK_MSG == groupNotificationDTO.getSendType()) {
            String title = groupNotificationDTO.getTheme();//title
            String linkPath = groupNotificationDTO.getLinkPath();
            textMsg = "{\"msgtype\":\"link\"," +
                    "\"link\":{\"text\":\" " + text + "\"," +
                    "\"title\":\"" + title + "\"," +
                    "\"picUrl\":\"\"," +
                    "\"messageUrl\":\"" + linkPath + "\"}" +
                    "}";
        }
        List<String> webhookURLs = groupNotificationDTO.getWebhookURL();
        if (webhookURLs != null) {
            for (String webhookURL : webhookURLs) {
                WEBHOOK_TOKEN = webhookURL;
                finalMsg = "群通知" + sendMessage(textMsg, WEBHOOK_TOKEN);
            }
        }


        return finalMsg;
    }


    public void sendFile(String[] url, String outfileName) throws IOException {

        String ip = "http://10.251.251.176:8080/groupMessageFileDownLoad";
        String title = "主题";
        String pictureURL = "[" + outfileName + "](" + ip + ")\n";
        String text = "";
        String linkPath = "";
        String textMsg = "{\n" +
                "    \"actionCard\": {\n" +
                "        \"text\": \"" + pictureURL +
                text + "\",\n" +
                "        \"hideAvatar\": \"0\", \n" +
                "    }, \n" +
                "    \"msgtype\": \"actionCard\"\n" +
                "}";
        for (String sUrl : url) {
            sendMessage(textMsg, sUrl);
        }

    }


    /**
     * 钉钉接口群消息发送
     */
    public void groupDepartmentNotification(GroupNotificationDTO groupNotificationDTO) throws Exception {
        if (null == groupNotificationDTO) {
            log.error("群发送消息异常！");
        }
        groupMessagePushService.push(groupNotificationDTO);
    }

    /**
     * 上传文件 返回mediaId
     *
     * @param file
     */
    public List<GroupNotificationDTO> DDFileUpload(CommonsMultipartFile file, HttpServletRequest request) throws Exception {
        List<GroupNotificationDTO> groupNotificationDTOList = new ArrayList<>();
        String pathHome = request.getSession().getServletContext().getRealPath("upload");
        File f = FileUtils.transferToServer(file, pathHome);
        Long fileSize = f.length();
        String fileName = f.getName();
        String[] strArr = fileName.split("\\.");
        String fileType = strArr[strArr.length - 1];

        GroupNotificationDTO groupNotificationDTO = new GroupNotificationDTO();
        String mediaType = "";
        if ("png".equals(fileType) || "jpeg".equals(fileType) || "jpg".equals(fileType)) {
            mediaType = MediaHelper.TYPE_IMAGE;
            if(fileSize>1048576L){     //图片不能超过1M
                log.error("群发送文件图片过大");
                throw new CommonException(ErrCodeConstant.FILE_SIZE_OUT,"上传图片不得超过1M");
            }
        } else {
            mediaType = MediaHelper.TYPE_FILE;
            if(fileSize>10485760L){     //文件不能超过10M
                log.error("群发送文件文件过大");
                throw new CommonException(ErrCodeConstant.FILE_SIZE_OUT,"上传文件不得超过10M");
            }
        }
        String mediaId = getMediaId(f, mediaType);
        groupNotificationDTO.setMediaType(mediaType);
        groupNotificationDTO.setMediaId(mediaId);
        groupNotificationDTO.setSendType(GroupMsgConstant.PIC_MSG);
        groupNotificationDTOList.add(groupNotificationDTO);

        return groupNotificationDTOList;
    }

    /**
     * 做群发送文件时注意多文件多个群 需要两次循环。
     * 队列发送不能for循环 push到队列里 有问题
     *
     * @param groupNotificationDTOs
     * @throws BaseException
     */
    public void DDFileUpSend(GroupNotificationSendDTO groupNotificationDTOs) throws BaseException {
        GroupNotificationDTO groupNotificationDTO = new GroupNotificationDTO();
        List<String> mediaTypeList = new ArrayList<>();
        List<String> mediaIdList = new ArrayList<>();
        groupNotificationDTO.setIds(groupNotificationDTOs.getIds());
        for(GroupNotificationDTO groupNotificationDTOData : groupNotificationDTOs.getData()){
            mediaTypeList.add(groupNotificationDTOData.getMediaType());
            mediaIdList.add(groupNotificationDTOData.getMediaId());
        }
        groupNotificationDTO.setMediaTypeList(mediaTypeList);
        groupNotificationDTO.setMediaIdList(mediaIdList);
        groupMessagePushService.push(groupNotificationDTO);
    }

    /**
     * @param groupNotificationDTO
     */
    public void DDLinkSend(GroupNotificationDTO groupNotificationDTO) throws BaseException, IOException, OApiException {
//        List<Long> ids = groupNotificationDTO.getIds();
//        for(Long id : ids){
//                GroupDO groupDO = (GroupDO) jedisUtils.getHashCache(CacheNameConstant.GROUP_ID_HASH,id+"");
//                String chatId = groupDO.getChatId();
//                String hookUrl = groupDO.getHookUrl();
//                if(!StringUtils.isEmpty(chatId)){
//                    MediaHelper.DDLinkSend(chatId,MediaHelper.TYPE_LINK,groupNotificationDTO);
//                }else if(!StringUtils.isEmpty(hookUrl)){
//                    List<String> hookUrls = new ArrayList<>();
//                    hookUrls.add(hookUrl);
//                    groupNotificationDTO.setWebhookURL(hookUrls);
//                    groupNotification(groupNotificationDTO);
//                }else{
//                    log.error("链接发送时此id的chatId和hookURL都为空:"+id);
//                }
//
//        }
        groupMessagePushService.push(groupNotificationDTO);
    }

    public void DDFileDownLoad() throws BaseException, OApiException, IOException {
        MediaHelper.downLoadByMediaId(AuthHelper.getAccessToken(), mediaId);
    }

    /**
     * 根据文件获取mediaId
     *
     * @param f
     * @return
     * @throws BaseException
     * @throws OApiException
     * @throws IOException
     */
    public String getMediaId(File f, String fileType) throws Exception {
        HttpResponse j = MediaHelper.getMediaId(AuthHelper.getAccessToken(), fileType, f);
        if (j == null) {
            log.error("测试media_id...........................:返回media_id为空");
            throw new GroupException(GroupMsgConstant.DING_MEDIA_ID, "获取media_id 时报错");
        }
        HttpEntity entity = j.getEntity();
        String resultStr = EntityUtils.toString(entity);
        JSONObject jsonObject = JSONObject.parseObject(resultStr);
        String mediaId = (String) jsonObject.get("media_id");
        return mediaId;
    }



    /**
     * 简化同步钉钉群主后，发送的消息通知
     * 1.新增群：显示新增群名称及群主名称
     * 2.修改群：显示修改群名称以及新增人员姓名 、删除人员姓名
     * 3.删除群：显示删除人员姓名以及群主，提醒删除  最好是额外的提醒
     */
    public void simplifySynchonizedGroupsMessage(int statusFlag, List<GroupDO> synchonizedGroupList) throws BaseException, OApiException, SdkInitException, ServiceNotExistException {
        if (null == synchonizedGroupList || statusFlag < 0) {
            log.error("发送同步群消息至钉钉群中错误！错误原因：缺失重要参数：" + synchonizedGroupList + "================群同步状态：" + statusFlag);
            return;
        }

        String syncGroupMsg = createSyncGroupMsg(statusFlag, synchonizedGroupList);
        //TODO 放到队列中
        if (null == syncGroupMsg || StringUtils.isEmpty(syncGroupMsg)) {
            log.error("发送消息失败！返回的消息为空！");
            return;
        }
        MessageBody.TextBody textBody = new MessageBody.TextBody();
        textBody.setContent(syncGroupMsg);
        /*
        *  下面注释不要删 为了测试同步之后发送同步之后的人员信息
        * */

//        if (CommonConstant.SERVER_VERSION == normalFlag) {
//            try{
//                ChatHelper.sendMessageToChat(AuthHelper.getAccessToken(), GroupConstant.NOTIFY_GROUP_CHATID, GroupConstant.BJC_SENDER, MessageType.TEXT, textBody);
//            }catch (ServiceException e){
//                log.error("系统繁忙,正式服务器群发消息失败");
//            }
//
//        } else {
//            try{
//                ChatHelper.sendMessageToChat(AuthHelper.getAccessToken(), GroupConstant.NOTIFY_GROUP_CHATID_TEST, GroupConstant.BJC_SENDER, MessageType.TEXT, textBody);
//            }catch (ServiceException e){
//                log.error("系统繁忙,测试服务器群发消息失败");
//            }
//
//        }
    }

    //同步群组，组织发送到官方群中的语言
    private String createSyncGroupMsg(int statusFlag, List<GroupDO> synchonizedGroupList) {
        StringBuilder msg = new StringBuilder();
        String notifyGroupTitle = GroupConstant.STATUS_GROUP_MSG_MAP.get(statusFlag);
        msg.append(notifyGroupTitle);
        for (GroupDO groupDO : synchonizedGroupList) {
            if (null == groupDO || StringUtils.isEmpty(groupDO.getOwnerId()) || StringUtils.isEmpty(groupDO.getGroupName())) {
                log.error("该群无法发送群同步消息！原因：缺失重要参数!群详情：" + groupDO);
            }
            msg.append("群名称：" + groupDO.getGroupName());

            if (!StringUtils.isEmpty(groupDO.getOwnerId())) {
                List<String> ownerIds = new ArrayList<>();
                ownerIds.add(groupDO.getOwnerId());
                msg.append("，群主：" + findEmpNameByUserId(ownerIds));
            }

            if (null != groupDO.getAddUserIds() && groupDO.getAddUserIds().size() > 0) {
                String addEmpNamesByUserIds = findEmpNameByUserId(groupDO.getAddUserIds());
                msg.append("，新增群成员：" + addEmpNamesByUserIds);
            }

            if (null != groupDO.getDelUserIds() && groupDO.getDelUserIds().size() > 0) {
                String addEmpNamesByUserIds = findEmpNameByUserId(groupDO.getAddUserIds());
                msg.append("， 删除群成员：" + addEmpNamesByUserIds);
            }
        }
        return msg.toString();
    }

    /**
     * 将userIDs转换成人名字符串列表
     * @param userIds
     * @return
     */
    private String findEmpNameByUserId(List<String> userIds) {
        if (null == userIds || userIds.size() < 1) {
            return null;
        }
        StringBuilder empNameListStr = new StringBuilder();    //将员工姓名组成一个字符串
        for (String oneUserId : userIds) {
            String empNameByUserId = null;
            try {
                empNameByUserId = employeesMapper.findEmpNameByUserId(oneUserId);
            } catch (Exception e) {
                log.error("查询群主时，sql执行错误。错误原因：" + e);
                continue;
            }
            if (null != empNameByUserId && !StringUtils.isEmpty(empNameByUserId)) {
                empNameListStr.append(empNameByUserId);
            }
        }
        return empNameListStr.toString();
    }
}



